package com.zs.propertymanage.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    // 数据库约束异常处理
//    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class) // 这个是Java的标准SQL异常，操作jdbc时会出现
    @ExceptionHandler(value = DataIntegrityViolationException.class)    // 这个是Spring框架的异常，捕获到数据访问层中的数据完整性违反异常时会出现
    public void handleForeignKeyConstraintViolation(SQLIntegrityConstraintViolationException ex, HttpServletResponse response) throws IOException {
        ex.printStackTrace();

//        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setStatus(HttpStatus.ACCEPTED.value());    // 201状态码表示请求被接受，但操作未完成
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "请确保无关联数据后再操作! ");
        map.put("code", HttpStatus.ACCEPTED.value());
        map.put("data", "此操作违反了数据库完整性约束条件");
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json);
    }

    // 顶层异常处理
    @ExceptionHandler(value = Exception.class)
    public void handleException(Exception ex, HttpServletResponse response) throws IOException {
        // 这里可以根据具体业务需求对异常进行分类处理
        ex.printStackTrace();

        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());    // http响应状态码为401
        Map<String, Object> map = new HashMap<>();
        map.put("msg", ex.getMessage());
        map.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
        map.put("data", null);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json);
    }

//    @ExceptionHandler(value = TransactionSystemException.class)
//    public void handleForeignKeyConstraintViolation(TransactionSystemException ex, HttpServletResponse response) throws IOException {
//        // 检查异常是否由外键约束失败引起
//        if (ex.getRootCause() instanceof SQLException &&
//                ((SQLException) ex.getRootCause()).getNextException() != null &&
//                (((SQLException) ex.getRootCause()).getNextException()).getSQLState().startsWith("23000")) { // 通常23000系列错误码与完整性约束相关
//
//            response.setStatus(HttpStatus.BAD_REQUEST.value()); // 通常将这类错误视为客户端请求错误，可设置为400 Bad Request
//            Map<String, Object> map = new HashMap<>();
//            map.put("msg", "数据库外键约束失败");
//            map.put("code", HttpStatus.BAD_REQUEST.value());
//            map.put("data", null);
//            String json = new ObjectMapper().writeValueAsString(map);
//            response.setContentType("application/json;charset=UTF-8");
//            response.getWriter().write(json);
//
//        } else {
//            // 其他类型的TransactionSystemException或其他未知异常，按照原有逻辑处理
//            this.handleException(ex, response);
//        }
//    }

}

